/*
 * mana (compiler)
 * Copyright (c) 2014 Shun Moriya <shun@mnu.sakura.ne.jp>
 *
 * The MIT License
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*!
 * @file
 * @brief	レジスタ割り当てに関するソースファイル
 *
 * このファイルは型情報に関係するソースファイルです。
 *
 * @author	Shun Moriya <shun@mnu.sakura.ne.jp>
 */

#if !defined(___MANA_INFO_H___)
#include "../library/mana_info.h"
#endif
#if !defined(___MANA_REGISTER_H___)
#include "mana_register.h"
#endif

static mana_register_entity entities[MANA_REGISTER_COUNT];

void mana_register_initialzie(void)
{
	size_t i;

	for(i = 0; i < MANA_REGISTER_COUNT; ++i)
	{
		mana_register_entity* entity = &entities[i];
		entity->symbol = NULL;
		entity->number = i;
	}
}

void mana_register_finalize(void)
{
	mana_register_clear();
}

void mana_register_clear(void)
{
	size_t i;

	for(i = 0; i < MANA_REGISTER_COUNT; ++i)
	{
		entities[i].symbol = NULL;
	}
}

mana_register_entity* mana_register_find(mana_symbol_entry* symbol)
{
	size_t i;

	for(i = 0; i < MANA_REGISTER_COUNT; ++i)
	{
		mana_register_entity* entity = &entities[i];
		if(entity->symbol == symbol)
		{
			return entity;
		}
	}

	return NULL;
}

/* TODO:無名レジスタの登録が必要
*/

mana_register_entity* mana_register_allocate(mana_symbol_entry* symbol, size_t address)
{
	size_t i;

	for(i = 0; i < MANA_REGISTER_COUNT; ++i)
	{
		mana_register_entity* entity = &entities[i];
		if(entity->symbol == NULL)
		{
			entity->symbol = symbol;
			entity->address = address;
			return entity;
		}
		else if(entity->symbol == symbol)
		{
			// already allocated
			return entity;
		}
	}

	return NULL;
}

void mana_register_release(mana_register_entity* entity)
{
	if(entity)
	{
		entity->symbol = NULL;
	}
}
